<template>
    <el-container class="jxc_stock_out_bill_container">
        <el-main>
            <el-card class="box-card">
                <headerTemplate slot="header" ref="header"
                                :table-ref="tableOptions.ref"
                                :toolbar_buttons="headerOption.toolbar_buttons"
                                :toolbar_filter="headerOption.toolbar_filter"
                                :searchForm="searchForm"
                                @event="handleHeaderEvent">
                    <template slot="right_search">
                        <el-select v-model="searchForm.warehouse_sid" placeholder="全部仓库"
                                   class="w100" clearable @change="getList(true)"
                                   style="margin-right: 5px;">
                            <el-option v-for="(item, index) in warehouseList"
                                       :key="index" :label="item.label" :value="item.value" />
                        </el-select>
                        <el-select v-model="searchForm.audit_state" placeholder="请选择"
                                   class="w100" clearable @change="getList(true)"
                                   style="margin-right: 5px;">
                            <el-option v-for="(item, index) in stateList"
                                       :key="index" :label="item.label" :value="item.value" />
                        </el-select>
                        <el-select v-model="searchForm.execute_state" placeholder="请选择"
                                   class="w100" clearable @change="getList(true)"
                                   style="margin-right: 5px;">
                            <el-option v-for="(item, index) in executeStateList"
                                       :key="index" :label="item.label" :value="item.value" />
                        </el-select>
                    </template>
                </headerTemplate>
                <div class="card_content">
                    <vxeTableTemplate :data="dataList" :options.sync="tableOptions"
                                      @event="handleTableEvent" />
                </div>
            </el-card>
        </el-main>
        <component-dialog dialog-drag :options="componentDialogExportOptions" />
        <component-dialog dialog-drag :options="componentDialogPrintOptions" />
    </el-container>
</template>

<script>
import { mapState } from "vuex";
import poiApi from "@common/api/poiApi";
import StockOutBillForm from "../dialog/StockOutBillForm";
import LogisticsForm from "../dialog/LogisticsForm";
import provide from "@common/mixins/provide";

export default {
    extends: provide,
    name: "JxcStockOutBill",
    data() {
        const _this = this;
        return {
            headerOption: {
                toolbar_buttons: [
                    {
                        id: "refresh",
                        icon: "el-icon-refresh-right",
                        show: true,
                        method: () => {
                            _this.getList();
                        },
                    },
                    {
                        id: "add",
                        icon: "fa fa-plus",
                        type: "primary",
                        show: true,
                        permission: "jxc:stockOutBill:save",
                        method: () => {
                            _this.openDialog(null, 'add');
                        },
                    },
                    {
                        id: "edit",
                        icon: "fa fa-pencil",
                        type: "success",
                        show: true,
                        permission: "jxc:stockOutBill:save",
                        method: () => {
                            _this.openDialog(null, 'edit');
                        },
                    },
                    {
                        id: "delete",
                        icon: "fa fa-trash-o",
                        type: "danger",
                        show: true,
                        permission: "jxc:stockOutBill:delete",
                        method: () => {
                            _this.deleteConfirm();
                        },
                    },
                    {
                        id: "audit",
                        label: '审核',
                        icon: "el-icon-top-right",
                        class: 'audit_btn',
                        show: true,
                        permission: "jxc:stockOutBill:audit",
                        method: () => {
                            _this.changeAuditState('audit');
                        },
                    },
                    {
                        id: "reAudit",
                        label: '反审',
                        icon: "el-icon-bottom-left",
                        class: 're_audit_btn',
                        show: true,
                        permission: "jxc:stockOutBill:reAudit",
                        method: () => {
                            _this.changeAuditState('reAudit');
                        },
                    },
                    {
                        id: "do_execute",
                        type: "success",
                        show: true,
                        label: '出库',
                        permission: "jxc:stockOutBill:execute",
                        method: () => {
                            _this.doExecute();
                        },
                    },
                    {
                        id: "export",
                        type: "warning",
                        icon: "el-icon-download",
                        label: '导出',
                        class: 'export_btn',
                        show: true,
                        permission: "jxc:stockOutBill:export",
                        btnType: 'dropdown',
                        dropdownItems: [
                            { command: 'includeDetail', label: '导出单据（含明细）' },
                            { command: 'noDetail', label: '导出单据（不含明细）' },
                        ],
                        method: command => {
                            _this.handleExportEvent(command);
                        },
                    },
                    {
                        id: "print",
                        icon: 'el-icon-printer',
                        show: true,
                        label: '打印',
                        class: 'print_btn',
                        permission: "jxc:stockOutBill:print",
                        btnType: 'print',
                        printType: 'stockOutBill',
                        dropdownItems: [
                            {
                                command: 'printTemplate',
                                label: '打印模板',
                                divided: true,
                                icon: 'el-icon-s-tools',
                                permission: 'jxc:stockOutBill:printTemplate'
                            },
                            {
                                command: 'printItem',
                                label: '打印配置项',
                                icon: 'el-icon-s-tools',
                                permission: 'jxc:stockOutBill:printItem'
                            },
                        ],
                        method: command => {
                            _this.handlePrintEvent(command);
                        },
                    },
                ],
                toolbar_filter: [
                    { type: "text", field: "code", label: "出库单号" },
                    { type: "daterange", field: "out_date", label: "出库日期", style: { width: '200px' }, },
                    { type: "text", field: "executor_name", label: "执行人" },
                    { type: "text", field: "src_code", label: "来源编号" },
                    { type: "daterange", field: "execute_date", label: "执行时间", style: { width: '200px' }, },
                    { type: "text", field: "goods_name", label: "物料名称" },
                ],
            },
            searchForm: {
                audit_state: '',
                execute_state: '',
            },
            warehouseList:[],
            dataList: [],
            selectionList: [],
            tableOptions: {
                ref: "JxcStockOutBillTable",
                container: ".jxc_stock_out_bill_container",
                multiSelect: true,
                showSummary: true,
                summaryArray: [ "out_qty" ],
                columns: [
                    {
                        label: "出库类型",
                        prop: "out_type",
                        align: "center",
                        width: 90,
                        formatter(row) {
                            let filter = _this.outTypeList.filter(item => item.value === row.out_type);
                            if (_this.$utils.isNotEmptyList(filter)) {
                                return filter[0].label;
                            }
                            return '';
                        },
                    },
                    {
                        label: "出库单号",
                        prop: "code",
                        align: "center",
                        minWidth: 150,
                    },
                    {
                        label: "出库日期",
                        prop: "out_date",
                        align: "center",
                        width: 90,
                    },
                    {
                        label: "客户",
                        prop: "client_display",
                        align: "center",
                        width: 100,
                    },
                    {
                        label: "供应商",
                        prop: "supplier_display",
                        align: "center",
                        width: 100,
                    },
                    {
                        label: "数据来源编号",
                        prop: "src_code",
                        align: "center",
                        minWidth: 100,
                    },
                    {
                        label: "仓库",
                        prop: "warehouse_name",
                        align: "center",
                        minWidth: 100,
                    },
                    {
                        label: "出库数量",
                        prop: "out_qty",
                        align: "center",
                        width: 110,
                    },
                    {
                        label: "审核状态",
                        prop: "audit_state",
                        align: "center",
                        formatter: (row) => {
                            if (_this.$utils.isNotEmpty(row.audit_state) && row.audit_state === 1) {
                                return '已审核';
                            }
                            return '待审核';
                        },
                    },
                    {
                        label: "审核人",
                        prop: "auditor_name",
                        align: "center",
                    },
                    {
                        label: "审核时间",
                        prop: "audit_date",
                        align: "center",
                        width: 140,
                    },
                    {
                        label: "执行状态",
                        prop: "execute_state",
                        align: "center",
                        formatter: (row) => {
                            if (_this.$utils.isNotEmpty(row.execute_state) && row.execute_state === 1) {
                                return '已执行';
                            }
                            return '待执行';
                        },
                    },
                    {
                        label: "执行人",
                        prop: "executor_name",
                        align: "center",
                    },
                    {
                        label: "执行出库时间",
                        prop: "execute_date",
                        align: "center",
                        width: 140,
                    },
                    {
                        label: "备注",
                        prop: "note_info",
                        align: "left",
                    },
                ],
                operates: {
                    fixed: "right",
                    list: [
                        {
                            id: "detail",
                            icon: "fa fa-info-circle",
                            type: "warning",
                            size: "mini",
                            show: true,
                            tooltip: {
                                content: "详情",
                            },
                            method: (index, row) => {
                                _this.openDialog(row, 'detail');
                            },
                        },
                        {
                            id: "out",
                            type: "success",
                            size: "mini",
                            label: '出库',
                            show: true,
                            permission: "jxc:stockOutBill:execute",
                            filter(row) {
                                return row.audit_state === 1 && row.execute_state === 0;
                            },
                            method: (index, row) => {
                                _this.doExecute(row);
                            },
                        },
                        {
                            id: "cancelout",
                            type: "error",
                            size: "mini",
                            label: '取消出库',
                            show: true,
                            permission: "jxc:stockOutBill:execute",
                            filter(row) {
                                return row.audit_state === 1 && row.execute_state === 1;
                            },
                            method: (index, row) => {
                                _this.cancelExecute(row);
                            },
                        },
                        {
                            id: "logistics",
                            type: "success",
                            size: "mini",
                            label: '物流',
                            show: true,
                            permission: "jxc:stockOutBill:logistics",
                            filter(row) {
                                return row.audit_state === 1 && row.execute_state === 1;
                            },
                            method: (index, row) => {
                                _this.openLogistics(row);
                            },
                        },
                        {
                            id: "edit",
                            icon: "fa fa-pencil",
                            type: "success ",
                            size: "mini",
                            show: true,
                            permission: "jxc:stockOutBill:save",
                            tooltip: {
                                content: "编辑",
                            },
                            filter(row) {
                                return row.audit_state === 0;
                            },
                            method: (index, row) => {
                                _this.openDialog(row, 'edit');
                            },
                        },
                        {
                            id: "del",
                            icon: "fa fa-trash-o",
                            type: "danger",
                            size: "mini",
                            show: true,
                            permission: "jxc:stockOutBill:delete",
                            tooltip: {
                                content: "删除",
                            },
                            filter(row) {
                                return row.audit_state === 0;
                            },
                            method: (index, row) => {
                                _this.deleteConfirm(row);
                            },
                        },
                    ],
                },
                pagination: {
                    pageIndex: 1,
                },
            },
            componentDialogExportOptions: {
                visible: false,
            },
            componentDialogPrintOptions: {
                visible: false,
            },
        };
    },
    computed: {
        ...mapState('jxc', [ 'stateList', 'executeStateList', 'outTypeList' ]),
    },
    mounted() {
        this.init();
    },
    methods: {
        handleHeaderEvent(event) {
            const _this = this;
            _this.searchForm = $.extend({}, _this.searchForm, event.searchForm);
            if (event.type === "search") {
                _this.getList(true);
            } else if (event.type === "refresh") {
                _this.getList(true);
            }
        },
        async init(){
            const _this = this;
            await _this.storeDispatch('jxc/initSetting');
            await _this.initWarehouseList();
            this.getList(true);
        },
        initWarehouseList() {
            const _this = this;
            return _this.fetchData(_this.$api.API_FindJxcStockWarehouses, {
                nopage: '1',
            }).then(res => {
                _this.warehouseList = (res.data || []).map(item => {
                    return {
                        value: item.sid,
                        label: item.name,
                    }
                });
            }).catch(() => {
            });
        },
        getList(query) {
            const _this = this;
            if (query) {
                _this.tableOptions = _this.resetTablePagination(_this.tableOptions);
            }
            let queryData = _this.getQueryParams(_this.tableOptions, _this.searchForm);
            _this.fetchData(_this.$api.API_FindJxcStockOutbills, queryData).then(result => {
                _this.dataList = result.data || [];
                _this.tableOptions = _this.setTableTotal(_this.tableOptions, result);
            }).catch(() => {
            });
        },
        handleTableEvent(event) {
            if (event.type === 'page') {
                this.getList();
                return;
            }
            if (event.type === 'selectionChange') {
                this.selectionList = event.value;
            }
        },
        openDialog(row, type) {
            const _this = this;
            if (type === 'edit' && row == null) {
                if (!_this.checkSelection(_this.selectionList, false)) {
                    return;
                }
                row = _this.selectionList[0];
            }
            if (!row) {
                row = {};
            }
            if (type === 'edit' && row.execute_state === 1) {
                _this.$message.error(`出库单：${ row.code } 已出库，无法再编辑！`);
                return;
            }
            if (type === 'edit' && row.audit_state === 1) {
                _this.$message.error(`出库单：${ row.code } 已审核，请先反审核再编辑！`);
                return;
            }
            let detail = type === 'detail' || row.audit_state === 1;
            _this.$dialog({
                title: '出库单',
                width: '1200px',
                component: {
                    value: StockOutBillForm,
                    props: {
                        row,
                        detail,
                    },
                },
                hideConfirmBtn: detail,
                confirmed() {
                    _this.getList();
                    _this.$bus.$emit('updateJxcDashboard');
                },
            });
        },
        deleteConfirm(row) {
            const _this = this;
            if (row && row.execute_state === 1) {
                _this.$message.error(`出库单：${ row.code } 已出库，无法删除`);
                return;
            }
            let filter = _this.selectionList.filter(item => item.execute_state === 1);
            if (_this.$utils.isNotEmptyList(filter)) {
                let codeList = filter.map(item => item.code);
                _this.$message.error(`出库单：${ codeList.join('、') } 已出库，无法删除`);
                return;
            }
            _this.storeDispatch('jxc/handleDeleteData', {
                url: _this.$api.API_DeleteJxcStockOutbills,
                row,
                list: _this.selectionList,
                _vm: _this,
                msg_name: '出库单',
                state_field: 'audit_state',
            }).then(res => {
                if (res) {
                    _this.getList();
                    _this.$bus.$emit('updateJxcDashboard');
                }
            });
        },
        changeAuditState(type) {
            const _this = this;
            let filter = _this.selectionList.filter(item => item.execute_state === 1);
            if (_this.$utils.isNotEmptyList(filter)) {
                let codeList = filter.map(item => item.code);
                _this.$message.error(`出库单：${ codeList.join('、') } 已出库，无法${ type === 'audit' ? '审核' : '反审' }`);
                return;
            }
            _this.storeDispatch('jxc/changeAuditState', {
                url: _this.$api.API_ChangeJxcStockOutbillAuditState,
                list: _this.selectionList,
                type,
                _vm: _this,
                msg_name: '出库单',
                state_field: 'audit_state',
            }).then(res => {
                if (res) {
                    _this.getList();
                }
            });
        },
        doExecute(row) {
            const _this = this;
            _this.storeDispatch('jxc/handleExecuteData', {
                url: _this.$api.API_ExecuteJxcStockOutbill,
                row,
                list: _this.selectionList,
                _vm: _this,
                msg_name: '出库单',
                isIning: false,
            }).then(res => {
                if (res) {
                    _this.getList();
                }
            });
        },

        cancelExecute(row) {
            const _this = this;
            _this.$confirm("是否确定取消出库吗？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                _this.fetchData(
                    _this.$api.API_CancelExecuteJxcStockOutbill,
                    {sid_list:[row.sid]}).then(res => {
                    if (res) {
                        _this.$message.success("取消出库成功！");
                        _this.getList();
                    }
                });
            })
                .catch(() => {
                });
        },
        openLogistics(row) {
            const _this = this;
            _this.$dialog({
                title: '物流信息',
                width: '600px',
                component: {
                    value: LogisticsForm,
                    props: {
                        row,
                    },
                },
                confirmed() {
                    _this.getList();
                },
            });
        },
        handleExportEvent(command) {
            const _this = this;
            let queryData = $.extend({}, _this.searchForm);
            queryData.dr = 0;
            let url = _this.$api.API_FindJxcStockOutbillsIncludeDetail;
            let outputName = '出库单（含明细）';
            let templateName = _this.$api.EXPORT_TEMPLATE_NAME_STOCK_OUT_BILL_INCLUDE_DETAIL;
            if (command === 'noDetail') {
                url = _this.$api.API_FindJxcStockOutbills;
                outputName = '出库单（不含明细）';
                templateName = _this.$api.EXPORT_TEMPLATE_NAME_STOCK_OUT_BILL_NO_DETAIL;
            }
            poiApi.exportExcelTemplate(templateName, url, queryData, outputName, {}, undefined, 1, 100, false, true).then(() => {
                return true;
            }).catch(() => {
                return false;
            });
        },
        handlePrintEvent(command) {
            const _this = this;
            if (command === 'printTemplate') {
                _this.$router.push({
                    path: '/print/stockOutBill',
                    query: {
                        name: '出库单',
                    },
                });
                return;
            }
            if (command === 'printItem') {
                _this.$router.push({
                    path: '/printItem/stockOutBill',
                    query: {
                        name: '出库单',
                    },
                });
                return;
            }
            if (!_this.checkSelection(_this.selectionList, true)) {
                return;
            }
            _this.$PrintPreview({
                template: command.sid,
                data: _this.selectionList,
                fetch(data) {
                    return _this.fetchData(_this.$api.API_QueryJxcStockOutBillData4Print, {
                        sid_list: data.map(item => item.sid),
                    }).then(result => {
                        return result.data || [];
                    }).catch(() => {
                        return [];
                    });
                },
            });
        },
    },
}
</script>

<style lang="less" rel="stylesheet/less" scoped>
.jxc_stock_out_bill_container {
    width: 100%;
    height: 100%;
}
</style>
